package com.adouteam.simple.wechat.msg;

import com.adouteam.simple.wechat.msg.basic.*;
import com.adouteam.simple.wechat.msg.event.*;
import com.adouteam.simple.wechat.service.ResponseService;

import javax.servlet.http.HttpServletResponse;
import java.util.EnumMap;
import java.util.Map;

/**
 * 自动回复用户信息处理器
 *
 * @author buxianglong
 **/
public class WechatMsgProcessor{
    /**
     * 观察者注册器
     */
    public static Map<WechatMsgType, MessageAble> ObserverRegister = new EnumMap<WechatMsgType, MessageAble>(WechatMsgType.class);

    /**
     * 初始化默认的观察者对象，需要主动调用，可以自定义新的观察者进行覆盖
     */
    static{
        ObserverRegister.put(WechatMsgType.TEXT, new TextMsg());
        ObserverRegister.put(WechatMsgType.IMAGE, new ImageMsg());
        ObserverRegister.put(WechatMsgType.VOICE, new VoiceMsg());
        ObserverRegister.put(WechatMsgType.VIDEO, new VideoMsg());
        ObserverRegister.put(WechatMsgType.SHORT_VIDEO, new ShortVideoMsg());
        ObserverRegister.put(WechatMsgType.LOCATION, new LocationMsg());
        ObserverRegister.put(WechatMsgType.LINK, new LinkMsg());

        ObserverRegister.put(WechatMsgType.EVENT_SUBSCRIBE, new SubscribeEventMsg());
        ObserverRegister.put(WechatMsgType.EVENT_UNSUBSCRIBE, new UnsubscribeEventMsg());
        ObserverRegister.put(WechatMsgType.EVENT_SCAN, new ScanEventMsg());
        ObserverRegister.put(WechatMsgType.EVENT_LOCATION, new LocationEventMsg());
        ObserverRegister.put(WechatMsgType.EVENT_MENU_CLICK, new MenuClickEventMsg());
        ObserverRegister.put(WechatMsgType.EVENT_MENU_VIEW, new MenuViewEventMsg());
    }

    /**
     * 根据消息，获取处理消息的观察者
     *
     * @param allMsg 综合消息体
     * @return 消息
     */
    public static MessageAble matchType(AllMsg allMsg){
        for(Map.Entry<WechatMsgType, MessageAble> entry : ObserverRegister.entrySet()){
            if(entry.getValue().isMe(allMsg)){
                return entry.getValue();
            }
        }
        return null;
    }

    /**
     * 自动回复用户消息
     *
     * @param allMsg 综合消息体
     * @param response 回复对象
     */
    public static void process(AllMsg allMsg, HttpServletResponse response){
        MessageAble messageAble = matchType(allMsg);
        if(null == messageAble){
            ResponseService.responseBlank(response);
        }
        messageAble.copyProperties(allMsg);
        messageAble.process(response);
    }
}
